//app.js
App({
  onLaunch() {
    this.syncCartToStorage();
    this.cart = wx.getStorageSync('cart');
    this.setBadge();
  },
  cart: wx.getStorageSync('cart') || [],
  badge: '',
  addToCart(cartItem) {
    console.log(this)
    const isInCart = this.cart.some(item => item.id === cartItem.id);
    if (isInCart) {
      this.cart = this.cart.map(item => {
        if (item.id === cartItem.id) {
          item.count += 1
        }
        return item
      })
    } else {
      this.cart = this.cart.concat({
        ...cartItem,
        count: 1
      })
    }
    this.syncCartToStorage();
    this.setBadge();
  },
  syncCartToStorage() {
    wx.setStorageSync('cart', this.cart)
  },
  setBadge() {
    const text = this.cart.reduce((result, item) => {
      result += item.count
      return result
    }, 0).toString();
    this.badge = text;
    wx.setStorage({
      key: 'badge',
      data: this.badge,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  }
})